/*
 * Copyright 2016 jeasonlzy(廖子尧)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.zhuike.novel.app.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.support.v4.media.MediaBrowserServiceCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import net.zhuike.novel.app.R;
import net.zhuike.novel.app.bean.BookFonts;
import net.zhuike.novel.app.bean.download.MyBusinessInfLocal;
import net.zhuike.novel.app.bean.local.ReadSettingManager;
import net.zhuike.novel.app.ui.activity.FontActivity;
import net.zhuike.novel.app.ui.base.adpter.BaseRecyclerViewAdapter;
import net.zhuike.novel.app.ui.utils.DBController;
import net.zhuike.novel.app.ui.utils.FileUtils;
import net.zhuike.novel.app.ui.utils.MyDownloadListener;

import java.io.File;
import java.lang.ref.SoftReference;
import java.sql.SQLException;

import framework.utils.downloader.DownloadService;
import framework.utils.downloader.callback.DownloadManager;
import framework.utils.downloader.domain.DownloadInfo;

import static framework.utils.downloader.domain.DownloadInfo.STATUS_COMPLETED;
import static framework.utils.downloader.domain.DownloadInfo.STATUS_REMOVED;
import static framework.utils.downloader.domain.DownloadInfo.STATUS_WAIT;

public class DownloadFontsAdapter extends
        BaseRecyclerViewAdapter<BookFonts, DownloadFontsAdapter.ViewHolder> {

    private static final String TAG = "DownloadListAdapter";
    private final FontActivity contexts;
    private final DownloadManager downloadManager;
    ReadSettingManager mSettingManager;
    private DBController dbController;
    public DownloadFontsAdapter(FontActivity context) {
        super(context);
        this.contexts = context;
        downloadManager = DownloadService.getDownloadManager(context.getApplicationContext());
        mSettingManager = ReadSettingManager.getInstance();
        try {
            dbController = DBController.getInstance(context.getApplicationContext());
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(contexts).inflate(
                R.layout.item_download_info, parent, false));
    }

    @Override
    public void onBindViewHolder(DownloadFontsAdapter.ViewHolder holder, final int position) {
        holder.bindData(getData(position), position, contexts);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(position);
                }
            }
        });
    }


    class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView tv_size;
        private final ProgressBar pb;
        private final TextView tv_name;
        private final Button bt_action;
        private DownloadInfo downloadInfo;

        public ViewHolder(View view) {
            super(view);
            itemView.setClickable(true);
            tv_size = (TextView) view.findViewById(R.id.tv_size);
            pb = (ProgressBar) view.findViewById(R.id.pb);
            tv_name = (TextView) view.findViewById(R.id.tv_name);
            bt_action = (Button) view.findViewById(R.id.bt_action);
        }
        @SuppressWarnings("unchecked")
        public void bindData(final BookFonts data, int position, final Context context) {
            tv_name.setText(data.getName());
            // Get download task status
            downloadInfo = downloadManager.getDownloadById(data.getUrl().hashCode());

            // Set a download listener
            if (downloadInfo != null) {
                downloadInfo
                        .setDownloadListener(new MyDownloadListener(new SoftReference(ViewHolder.this)) {
                            //  Call interval about one second
                            @Override
                            public void onRefresh() {
                                if (getUserTag() != null && getUserTag().get() != null) {
                                    ViewHolder viewHolder = (ViewHolder) getUserTag().get();
                                    viewHolder.refresh();
                                }
                            }
                        });

            }

            refresh();

//      Download button
            bt_action.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (downloadInfo != null) {

                        switch (downloadInfo.getStatus()) {
                            case DownloadInfo.STATUS_NONE:
                            case DownloadInfo.STATUS_PAUSED:
                            case DownloadInfo.STATUS_ERROR:

                                //resume downloadInfo
                                downloadManager.resume(downloadInfo);
                                break;

                            case DownloadInfo.STATUS_DOWNLOADING:
                            case DownloadInfo.STATUS_PREPARE_DOWNLOAD:
                            case STATUS_WAIT:
                                //pause downloadInfo
                                downloadManager.pause(downloadInfo);
                                break;
                            case STATUS_COMPLETED:
                                mSettingManager.setTypeface(downloadInfo.getPath());
                                contexts.setResult(10086,new Intent().putExtra("path",downloadInfo.getPath()));
                                contexts.finish();
                                break;
                        }
                    } else {
//            Create new download task
                        File d = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "d");
                        if (!d.exists()) {
                            d.mkdirs();
                        }
                        String path = d.getAbsolutePath().concat("/").concat(data.getName());
                        downloadInfo = new DownloadInfo.Builder().setUrl(data.getUrl())
                                .setPath(path)
                                .build();
                        downloadInfo
                                .setDownloadListener(new MyDownloadListener(new SoftReference(ViewHolder.this)) {

                                    @Override
                                    public void onRefresh() {
                                        notifyDownloadStatus();

                                        if (getUserTag() != null && getUserTag().get() != null) {
                                            ViewHolder viewHolder = (ViewHolder) getUserTag().get();
                                            viewHolder.refresh();
                                        }
                                    }
                                });
                        downloadManager.download(downloadInfo);

                        //save extra info to my database.
                        MyBusinessInfLocal myBusinessInfLocal = new MyBusinessInfLocal(
                                data.getUrl().hashCode(), data.getName(), data.getUrl());
                        try {
                            dbController.createOrUpdateMyDownloadInfo(myBusinessInfLocal);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });

        }

        private void notifyDownloadStatus() {
            if (downloadInfo.getStatus() == STATUS_REMOVED) {
                try {
                    dbController.deleteMyDownloadInfo(downloadInfo.getUri().hashCode());
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }

        private void refresh() {
            if (downloadInfo == null) {
                tv_size.setText("");
                pb.setProgress(0);
                bt_action.setText("下载");
            } else {
                switch (downloadInfo.getStatus()) {
                    case DownloadInfo.STATUS_NONE:
                        bt_action.setText("下载");
                        break;
                    case DownloadInfo.STATUS_PAUSED:
                    case DownloadInfo.STATUS_ERROR:
                        bt_action.setText("继续");
                        try {
                            pb.setProgress((int) (downloadInfo.getProgress() * 100.0 / downloadInfo.getSize()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        tv_size.setText(FileUtils.formatFileSize(downloadInfo.getProgress()) + "/" + FileUtils
                                .formatFileSize(downloadInfo.getSize()));
                        break;

                    case DownloadInfo.STATUS_DOWNLOADING:
                    case DownloadInfo.STATUS_PREPARE_DOWNLOAD:
                        bt_action.setText("暂停");
                        try {
                            pb.setProgress((int) (downloadInfo.getProgress() * 100.0 / downloadInfo.getSize()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        tv_size.setText(FileUtils.formatFileSize(downloadInfo.getProgress()) + "/" + FileUtils
                                .formatFileSize(downloadInfo.getSize()));
                        break;
                    case STATUS_COMPLETED:
                        bt_action.setText("使用");
                        try {
                            pb.setProgress((int) (downloadInfo.getProgress() * 100.0 / downloadInfo.getSize()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        tv_size.setText(FileUtils.formatFileSize(downloadInfo.getProgress()) + "/" + FileUtils
                                .formatFileSize(downloadInfo.getSize()));
                        break;
                    case STATUS_REMOVED:
                        tv_size.setText("");
                        pb.setProgress(0);
                        bt_action.setText("下载");
                    case STATUS_WAIT:
                        tv_size.setText("");
                        pb.setProgress(0);
                        bt_action.setText("暂停");
                        break;
                }

            }
        }
    }
}
